package com.atguigu;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.LoggerFactory;

import ch.qos.logback.core.joran.conditional.ElseAction;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.Transaction;

public class SecKill_redis {


    public static void main(String[] args) {

    }


    //秒杀过程
    public static boolean doSecKill(String uid, String prodid) throws IOException {
        //uid prodid 非空判断
        if (uid == null || prodid == null) {
            System.out.println(uid + " : " + prodid);
            return false;
        }
        //连接redis
//        Jedis jedis = new Jedis("101.43.5.132", 6379);
        JedisPool jedisPoolInstance = JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis = jedisPoolInstance.getResource();
        //库存key
        String kcKey = "sk:" + prodid + ":qt";
        //秒杀成功用户key
        String userKey = "sk:" + prodid + ":user";

        jedis.watch(kcKey);
        //获取库存，如果库存为null，秒杀还未开始
        String kc = jedis.get(kcKey);
        if (kc == null) {
            System.out.println("秒杀还未开始，请等待");
            jedis.close();
            return false;
        }

        //判断用户是否重复秒杀
        if (jedis.sismember(userKey, uid)) {
            System.out.println("已经秒杀成功了,不能重复秒杀");
            jedis.close();
            return false;
        }

        //如果商品库存小于1，秒杀结束
        if (Integer.parseInt(kc) < 1) {
            System.out.println("秒杀已经结束了");
            jedis.close();
            return false;
        }

        //秒杀过程
        //使用事务
        Transaction multi = jedis.multi();
        //组队操作
        multi.decr(kcKey);
        multi.sadd(userKey, uid);
        //执行
        List<Object> results = multi.exec();
        if (results == null || results.size() == 0) {
            System.out.println("秒杀失败了...");
            jedis.close();
            return false;
        }


        //库存减一
//        jedis.decr(kcKey);
        //把秒杀成功用户添加到清单中
//        jedis.sadd(userKey,uid);
        System.out.println("秒杀成功了...");
        jedis.close();

        return true;
    }
}
